import getUserID from "@/utils/userTempld"
import {
    GetCode,
    GetUserRegister,
    GetUserLogin,
    GetUserInfo,
    outlogin
} from "@/api"
import {
    Promise
} from "core-js";

const actions = {
    async getCode(ministore, phone) {
        const re = await GetCode(phone)
        if (re.code === 200) {
            return re.data
        } else {
            return Promise.reject(new Error("获取验证码失败"))
        }
    },
    async UserRegister(ministore, userInfo) {
        const re = await GetUserRegister(userInfo)
        if (re.code === 200) {
            return Promise.resolve("注册成功")
        } else {
            return Promise.reject(new Error(re.code))
        }
    },

    //登录后返回登录标识信息
    async UserLogin(ministore, userInfo) {
        const re = await GetUserLogin(userInfo)
        if (re.code === 200) {
            localStorage.setItem("token_key", re.data.token)
            ministore.commit("SET_TOKEN_STATE", re.data.token)
            return Promise.resolve("登录成功")
        } else {
            return Promise.reject(new Error(re.message))
        }
    },

    //获取用户信息
    async UserInfo(ministore) {
        const re = await GetUserInfo()
        if (re.code === 200) {
            ministore.commit("SET_USERINFO_STATE", re.data)
            return Promise.resolve("ok")
        } else {
            return Promise.reject(new Error(re.message))
        }
    },

    //退出登录
    async Out(ministore) {
        const re = await outlogin()
        if (re.code === 200) {
            return Promise.resolve()
        } else {
            return Promise.reject(new Error(re.message))
        }
    },
    clear(ministore) {
        localStorage.removeItem("token_key")
        ministore.commit("CLEAR_TOKEN_STATE")
    }
};
const mutations = {
    SET_TOKEN_STATE(state, value) {
        state.token = value;
    },
    SET_USERINFO_STATE(state, value) {
        state.userInfo = value
    },
    CLEAR_TOKEN_STATE(state) {
        state.token = "",
            state.userInfo = ""
    }
};
const state = {
    userTempId: getUserID(),
    token: localStorage.getItem("token_key"),
    userInfo: ""
}
const getters = {};


export default {
    actions,
    mutations,
    state,
    getters
}